var express = require('express');
var router = express.Router();
var fs = require('fs')
var bank_list = require('../utils/bank_list')
var pfxContent = fs.readFileSync("../config/apiclient_cert.p12")
var moment = require('moment')
var result = require('../utils/result')
let axios = require('axios')
var Task = require('../model/task');
let User=require('../model/user')
var Task_pay_logs = require('../model/task_pay_logs');
var Task_bill = require('../model/task_bill')
var Task_sign = require('../model/task_sign')
var WXPay = require('weixin-pay');
var wxpay = WXPay({
    appid: 'wx838cf54dd030d93a',
    mch_id: '1511866921',
    partner_key: 'zxzxskzxskizxskilzxskillzxskill1', //微信商户平台API密钥
    pfx: fs.readFileSync('../config/apiclient_cert.p12'), //微信商户平台证书
});

router.all('/api/wxpay', async (req, res)=> {

    /*
    https://github.com/tvrcgo/weixin-pay
     */
    let sign_cash = await Task_sign.findOne({where:{sigin_id:req.query.sigin_id,task_id:req.query.task_id}});
    let task = Task.findOne({where:{task_id:req.query.task_id}});
    let total_fee =(Number(sign_cash.sign_cash) * 100 )+((Number(sign_cash.sign_cash) * 100 )*0.15);
    // let total_fee =1
    wxpay.getBrandWCPayRequestParams({
        openid: req.query.openid,
        body: req.query.body,
        detail: req.query.detail,
        out_trade_no: req.query.out_trade_no,
        total_fee: total_fee,
        spbill_create_ip: '192.168.2.210',
        notify_url: 'http://m.zxskill.com'
    }, function (err, result) {
        // in express
        console.log(result)
        Task_pay_logs.create({
            pay_money: req.query.total_fee,
            pay_detail: req.query.detail,
            remark: req.query.remark || `支付任务(id:${req.query.task_id})的赏金支付`,
            uid: req.query.uid,
            task_id: req.query.task_id
        })
        res.status(200).json(result)
    });

})

router.all('/api/wxpay/result', async (req, res)=> {
    let out_trade_no = req.query.out_trade_no;
    let uid = req.query.uid;
    let task_id = req.query.task_id;
    let belong = req.query.belong;
    let sigin_id = req.query.sigin_id;
    let task_sign = await Task_sign.findOne({sigin_id:sigin_id,task_id:task_id})

    let sign_list = await Task_sign.findAll({where:{task_id:task_id}});

    Task_bill.findOne({where: {task_id: task_id}}).then(task_bill => {
        wxpay.queryOrder({out_trade_no: out_trade_no}, function (err, order) {
            if (!err) {
                console.log(order)
                if (!task_bill) {
                    Task_bill.create({
                        out_trade_no:out_trade_no,
                        uid: uid,
                        task_id: task_id,
                        status: order.return_code,
                        bill_money: order.cash_fee,
                        type: req.query.type || '任务支付',

                    })
                };

                Task.update({status:4,belong:belong,isPay:1,task_price:task_sign.sign_cash,task_pay:order.cash_fee},{where:{task_id:task_id,uid:uid,isDel:0}});
                Task_sign.update({isDel:1},{where:{task_id:task_id}});
                User.findOne({where:{uid:sigin_id}}).then(user=>{
                    axios.get('http://localhost:3000/wx/message',{params: {
                            openid: user.openid,
                            model:'signG'
                        }});
                })
                res.status(200).json(result(0, 'success', order))
                sign_list.forEach(function (el,idx) {
                    if(el.sigin_id ==sigin_id){
                        return;
                    }else{
                        User.findOne({where:{uid:el.sigin_id}}).then(rps=>{
                            axios.get('http://localhost:3000/wx/message',{params: {
                                    openid: rps.openid,
                                    model:'sign_fail',
                                    id:task_id
                                }});
                        })
                    }


                })

            } else {
                res.status(200).json(result(-1, '查询失败'))
            }
        });
    });


})

module.exports = router;
